<?php



/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Game
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */
 
 
 
class Game_Model_DbTable_Favorites extends Engine_Db_Table
{
  protected $_rowClass = "Game_Model_Favorite";
  
  
  public function getFavoriteTable()
  {
    return $this;
  }
 

  public function updatePreferenceCountKeys(Game_Model_Game $game)
  {
    $game->favorite_count = $this->getFavoriteCount($game, false);
    $game->save();    
  }
  
  
  public function addFavorite(Game_Model_Game $game, User_Model_User $user)
  {
    $row = $this->getUserFavorite($game, $user);
    if( null !== $row )
    {
      throw new Game_Model_Exception('Already favorited');
    }

    $table = $this;
    $row = $table->createRow();

    $row->game_id = $game->getIdentity();
    $row->user_id = $user->getIdentity();
    $row->save();

    $this->updatePreferenceCountKeys($game);
    
    return $row;
  }

  public function removeFavorite(Game_Model_Game $game, User_Model_User $user)
  {
    $row = $this->getUserFavorite($game, $user);
    if( null === $row )
    {
      throw new Game_Model_Exception('No favorite to remove');
    }
    
    $row->delete();

    $this->updatePreferenceCountKeys($game);
    
    return $this;
  }

  
  
  public function isFavorite(Game_Model_Game $game, User_Model_User $user)
  {
    return ( null !== $this->getUserFavorite($game, $user) );
  }

  public function getUserFavorite(Game_Model_Game $game, User_Model_User $user)
  {
    static $favorites;
    
    if (!$user->getIdentity())
    {
      return null;
    }
    else if (isset($favorites[$game->getIdentity()][$user->getIdentity()]))
    {
      $favorite = $favorites[$game->getIdentity()][$user->getIdentity()];
    }
    else {
      $params = array(
      	'user' => $user
      );
  
      $favorite = $this->getFavorite($game, $params);
      $favorites[$game->getIdentity()][$user->getIdentity()] = $favorite;
    }
    
    return $favorite;
  }

  public function getFirstFavorite(Game_Model_Game $game)
  {
  	$params = array(
  		'order' => 'oldest',
  	);

  	$favorite = $this->getFavorite($game, $params);
  	
  	return $favorite;
  }
  
  public function getFavorite(Game_Model_Game $game, $params = array())
  {
  	$select = $this->getFavoriteSelect($game, $params);
  	$select->limit(1);

  	$favorite = $this->fetchRow($select);
  	
  	return $favorite;
  }
  
  public function getFavoritesPaginator($params = array())
  {
    $paginator = Zend_Paginator::factory($this->_getFavoritesSelect($params));
    
    if( !empty($params['page']) )
    {
      $paginator->setCurrentPageNumber($params['page']);
    }
    if( !empty($params['limit']) )
    {
      $paginator->setItemCountPerPage($params['limit']);
    }    
    
    return $paginator;
  }
  
  protected function _getFavoritesSelect($params = array())
  {
    $select = $this->select();
    
    if (isset($params['game']))
    {
      $game_id = ($params['game'] instanceof Game_Model_Game) ? $params['game']->getIdentity() : $params['game'];
      $select->where('game_id = ?', $game_id);
    }

    if (isset($params['user']))
    {
      $user = Engine_Api::_()->user()->getUser($params['user']);
      $select->where('user_id = ?', $user->getIdentity());
    }
    
    if (empty($params['order'])) 
    {
      $params['order'] = 'recent';
    }    
    
    if (isset($params['order'])) 
    {
      switch ($params['order'])
      {
        case 'random':
          $order_expr = new Zend_Db_Expr('RAND()');
          break;
        case 'recent':
          $order_expr = "creation_date DESC";
          break;
        case 'oldest':
          $order_expr = "creation_date ASC";
          break;
        default:
          $order_expr = !empty($params['order']) ? $params['order'] : 'creation_date DESC';
          
          if (!empty($params['order_direction'])) {
            $order_expr .= " " .$params['order_direction'];
          }
      }
      $select->order( $order_expr );
    }    

    return $select;
  }
  
  public function getFavoriteSelect(Game_Model_Game $game, $params = array())
  {
    $params = array_merge($params, array('game' => $game));
    $select = $this->_getFavoritesSelect($params);   

    return $select;
  }

  public function getFavoritePaginator(Game_Model_Game $game, $params = array())
  {
    $params = array_merge($params, array('game' => $game));
    $paginator = $this->getFavoritesPaginator($params);
    
    return $paginator;
  }

  public function getFavoriteCount(Game_Model_Game $game, $cache = true)
  {
    if( isset($game->favorite_count) && $cache )
    {
      return $game->favorite_count;
    }

    $select = new Zend_Db_Select($this->getAdapter());
    $select
      ->from($this->info('name'), new Zend_Db_Expr('COUNT(1) as count'));

    $select->where('game_id = ?', $game->getIdentity());
    
    $data = $select->query()->fetchAll();
    return (int) $data[0]['count'];
  }

  public function getAllFavorites(Game_Model_Game $game)
  {
    return $this->fetchAll($this->getFavoriteSelect($game));
  }

  
  public function getAllFavoritesUsers(Game_Model_Game $game)
  {
    $table = $this;
    $select = new Zend_Db_Select($table->getAdapter());
    $select->from($table->info('name'), array('user_id', 'favorite'));

    $select->where('game_id = ?', $game->getIdentity());
    
    $users = array();
    foreach( $select->query()->fetchAll() as $data )
    {
      $users[] = $data['user_id'];
    }
    $users = array_values(array_unique($users));

    return Engine_Api::_()->getItemMulti('user', $users);
  }
  
  
}